# -*- coding: utf-8 -*-
import numpy as np
import cv2

def cv_show(img, name, writename):  #
    cv2.imshow(name, img)
    cv2.imwrite(writename, img)
    cv2.waitKey()
    cv2.destroyAllWindows()
# 读取图片
img = cv2.imread('contours.png')
# 灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 对灰度图二值化
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 绘制图像轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
# 取第三个轮廓结果
cnt = contours[3]
# 边界矩形轮廓函数
#可根据得到的数据绘制出边界矩形
x,y,w,h = cv2.boundingRect(cnt)
img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

#轮廓面积与边界矩形比
# area = cv2.contourArea(cnt)
# x,y,w,h = cv2.boundingRect(cnt)#可根据得到的数据绘制出外接圆
#
# rect_area = w*h
# extern = float(area)/rect_area#轮廓面积与边界矩形比
# print(extern)

#外接圆
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)
#画圆函数
img2 = cv2.circle(img,center,radius,(0,0,255),2)
cv_show(img2,'img2','img2.png')